package com.example.librarysystem.Controller;

import com.example.librarysystem.Service.*;
import com.example.librarysystem.entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Controller
@Api(value = "读者控制器接口")
public class BorrowerController {
    @Autowired
    private BooksService booksService;
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private StarService starService;
    @Autowired
    private TimesService timesService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CreditService creditService;

    @ApiOperation(value = "读者欢迎界面")
    @GetMapping("/borrowerWelcome")
    public String borrowerWelcome(Model model, HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        Integer borrowerNum = borrowerService.selectCount();
        Integer borrowNum = borrowService.selectCount();
        Integer commentNum = commentService.selectCount();
        Integer bookNum = booksService.selectCount();
        model.addAttribute("borrowerNum", borrowerNum);
        model.addAttribute("borrowNum",borrowNum);
        model.addAttribute("commentNum",commentNum);
        model.addAttribute("bookNum",bookNum);
        return "page/borrowerWelcome";
    }

    @ApiOperation(value = "读者个人信息")
    @GetMapping("/borrowerInfo")
    public String borrowerInfo(Model model, HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        int id = (int)request.getSession().getAttribute("id");
        Borrower borrower = borrowerService.selectById(id);
        //System.out.println(borrower);
        model.addAttribute("borrower", borrower);
        return "borrower/borrowerInfo";
    }
    @ApiOperation(value = "读者修改个人信息")
    @PostMapping("/updateBorrowerInfo")
    @ResponseBody
    public R updateBorrowerInfo(HttpServletRequest request,
                                @RequestParam("address") String address,
                                @RequestParam("phone") String phone){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        String name = (String)request.getSession().getAttribute("name");
        Borrower borrower = borrowerService.selectByName(name);
        borrower.setAddress(address);
        borrower.setPhoneNum(phone);
        if(borrowerService.updateBorrowerAddressAndPhone(borrower) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后再试");
        }
    }
    @ApiOperation(value = "读者修改邮箱")
    @PostMapping("/updateBorrowerEmail")
    @ResponseBody
    public R updateBorrowerEmail(HttpServletRequest request,
                                @RequestParam("email") String email){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        String name = (String)request.getSession().getAttribute("name");
        Borrower borrower = borrowerService.selectByName(name);
        borrower.setEmail(email);
        if(borrowerService.updateBorrowerEmail(borrower) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后再试");
        }
    }
    @ApiOperation(value = "读者修改密码")
    @PostMapping("/updateBorrowerPassword")
    @ResponseBody
    public R updateBorrowerPassword(HttpServletRequest request,
                                    @RequestParam("oldPassword") String oldPassword,
                                    @RequestParam("password") String password){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        String name = (String)request.getSession().getAttribute("name");
        Borrower borrower = borrowerService.selectByName(name);
        if(!oldPassword.equals(borrower.getPassword())){
            return R.fail("原密码错误");
        }
        borrower.setPassword(password);
        if(borrowerService.updateBorrowerPassword(borrower) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后再试");
        }
    }
    @ApiOperation(value = "读者预约操作")
    @GetMapping("/borrowerOrder")
    public String borrowerOrder(HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if(isLongin == null || !isLongin.equals("1")){
            return "notLogin";
        }
        return "borrower/borrowerOrder";
    }
    @ApiOperation(value = "读者预约详情")
    @GetMapping("/borrowerOrderInfo")
    @ResponseBody
    public JsonObject borrowerOrderInfo(int page, int limit, HttpServletRequest request){
        String bookName=request.getParameter("name");
        String author=request.getParameter("author");
        String publishingHouse = request.getParameter("publishingHouse");
        int borrowerId = (int)request.getSession().getAttribute("id");
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        List<OrderInfo> orderInfo = null;
        if(bookName == null && author == null && publishingHouse == null){
            orderInfo = orderService.selectOrderInfo(borrowerId, page, limit);
            jsonObject.setCount((long)orderService.selectOrderInfoCount(borrowerId));
        }else {
            bookName = "%"+bookName+"%";
            author = "%"+author+"%";
            publishingHouse = "%"+publishingHouse+"%";
            orderInfo = orderService.selectOrderInfoSearch(borrowerId,bookName,author,publishingHouse,page,limit);
            jsonObject.setCount((long)orderService.selectOrderInfoSearchCount(borrowerId,bookName,author,publishingHouse));
        }
        jsonObject.setData(orderInfo);

        //System.out.println(orderInfo);
        return jsonObject;
    }
    @ApiOperation(value = "读者借阅操作")
    @GetMapping("/borrowerBorrow")
    public String borrowerBorrow(HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if(isLongin == null || !isLongin.equals("1")){
            return "notLogin";
        }
        return "borrower/borrowerBorrow";
    }
    @ApiOperation(value = "读者借阅详情")
    @GetMapping("/borrowerBorrowInfo")
    @ResponseBody
    public JsonObject borrowerBorrow(int page, int limit, HttpServletRequest request){
        String bookName=request.getParameter("name");
        String author=request.getParameter("author");
        String publishingHouse = request.getParameter("publishingHouse");
        int borrowerId = (int)request.getSession().getAttribute("id");
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        List<BorrowInfo> borrowInfo = null;
        if(bookName == null && author == null && publishingHouse == null){
            borrowInfo = borrowService.selectBorrowInfo(borrowerId, page, limit);
            jsonObject.setCount((long)borrowService.selectBorrowInfoCount(borrowerId));
        }else {
            bookName = "%"+bookName+"%";
            author = "%"+author+"%";
            publishingHouse = "%"+publishingHouse+"%";
            borrowInfo = borrowService.selectBorrowInfoSearch(borrowerId,bookName,author,publishingHouse,page,limit);
            jsonObject.setCount((long)borrowService.selectBorrowInfoSearchCount(borrowerId,bookName,author,publishingHouse));
        }
        for (BorrowInfo info : borrowInfo) {
            String is = info.getIsReturn();
            if (is.equals("1")) {
                info.setIsReturn("是");
            } else {
                info.setIsReturn("否");
            }

        }
        jsonObject.setData(borrowInfo);
        return jsonObject;
    }
    @ApiOperation(value = "读者取消预约")
    @PostMapping("/deleteOrder")
    @ResponseBody
    public R deleteOrder(@RequestParam("id") Integer id, HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        //System.out.println(id);
        if(orderService.deleteOrderById(id) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后重试");
        }
    }
    @ApiOperation(value = "读者收藏图书")
    @GetMapping("/borrowerStar")
    public String borrowerStar(HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if(isLongin == null || !isLongin.equals("1")){
            return "notLogin";
        }
        return "borrower/borrowerStar";
    }
    @ApiOperation(value = "读者收藏详情")
    @GetMapping("/borrowerStarInfo")
    @ResponseBody
    public JsonObject borrowerStarInfo(int page, int limit, HttpServletRequest request){
        String bookName=request.getParameter("name");
        String author=request.getParameter("author");
        String publishingHouse = request.getParameter("publishingHouse");
        int borrowerId = (int)request.getSession().getAttribute("id");
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        List<StarInfo> starInfo = null;
        if(bookName == null && author == null && publishingHouse == null){
            starInfo = starService.selectStarInfo(borrowerId, page, limit);
            jsonObject.setCount((long)starService.selectStarInfoCount(borrowerId));
        }else {
            bookName = "%"+bookName+"%";
            author = "%"+author+"%";
            publishingHouse = "%"+publishingHouse+"%";
            starInfo = starService.selectStarInfoSearch(borrowerId,bookName,author,publishingHouse,page,limit);
            jsonObject.setCount((long)starService.selectStarInfoSearchCount(borrowerId,bookName,author,publishingHouse));
        }
        jsonObject.setData(starInfo);
        //System.out.println(starInfo);
        return jsonObject;
    }
    @ApiOperation(value = "读者取消收藏")
    @PostMapping("/deleteStar")
    @ResponseBody
    public R deleteStar(@RequestParam("id") Integer id, HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        //System.out.println(id);
        if(starService.deleteStarById(id) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后重试");
        }
    }
    @ApiOperation(value = "读者书评操作")
    @GetMapping("/borrowerComment")
    public String borrowerComment(HttpServletRequest request) {
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        return "borrower/borrowerComment";
    }
    @ApiOperation(value = "读者书评详情")
    @GetMapping("/borrowerCommentInfo")
    @ResponseBody
    public JsonObject borrowerCommentInfo(int page, int limit, HttpServletRequest request){
        String bookName=request.getParameter("bookName");
        String author=request.getParameter("author");
        String publishingHouse = request.getParameter("publishingHouse");
        int borrowerId = (int)request.getSession().getAttribute("id");
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        List<CommentInfo> commentInfo = null;
        if(bookName == null && author == null && publishingHouse == null){
            commentInfo = commentService.selectCommentInfo(borrowerId, page, limit);
            jsonObject.setCount((long)commentService.selectCommentInfoCount(borrowerId));
        }else {
            bookName = "%"+bookName+"%";
            author = "%"+author+"%";
            publishingHouse = "%"+publishingHouse+"%";
            commentInfo = commentService.selectCommentInfoSearch(borrowerId,bookName,author,publishingHouse,page,limit);
            jsonObject.setCount((long)commentService.selectCommentInfoSearchCount(borrowerId,bookName,author,publishingHouse));
        }
        jsonObject.setData(commentInfo);
        //System.out.println(commentInfo);
        return jsonObject;
    }
    @ApiOperation(value = "读者删除书评")
    @PostMapping("/deleteComment")
    @ResponseBody
    public R deleteComment(@RequestParam("id") Integer id,
                           @RequestParam("bookName") String bookName,
                           @RequestParam("score") Integer score,
                           HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        //System.out.println(id);
        if(commentService.deleteCommentById(id,score,bookName) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后重试");
        }
    }
    @ApiOperation(value = "读者查看图书")
    @GetMapping("/borrowerBookShow")
    public String borrowerBookShow(HttpServletRequest request){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        return "borrower/borrowerBookShow";
    }
    @ApiOperation(value = "读者查看图书详情")
    @GetMapping("/borrowerBooksDetail")
    public String visitorBooksDetail(@RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "name", required = false) String name,
                                     Model model, HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        Integer borrowerId = (Integer)request.getSession().getAttribute("id");
        Books books = null;
        if(id != null){
            books = booksService.selectById(id);
        }else {
            books = booksService.selectByNameOnly(name);
        }
        if(books != null){
            //System.out.println(books);
            Times times = timesService.selectByName(books.getName());
            times.setClickTimes(times.getClickTimes() + 1);
            timesService.updateClickTimes(times);
            Comment comment = commentService.selectCommentByBookAndBorrower(books.getName(),borrowerId);
            //System.out.println(comment);
            List<Books> booksList = booksService.selectByISBN1(books.getISBN());
            //System.out.println(booksList);
            List<Books> sameBorrow = booksService.selectBySameBorrower(books.getName());
            List<Books> sameStar = booksService.selectBySameStar(books.getName());
            Integer star = starService.selectCountByBookName(books.getName());
            Integer borrow = borrowService.selectCountByBookName(books.getName());
            List<Comment> commentList = commentService.selectByBookName(books.getName());
            for (Comment c : commentList) {
                String temp = c.getBorrowerName().substring(0, 1);
                temp = temp + "**";
                c.setBorrowerName(temp);
            }
            model.addAttribute("books", books);
            model.addAttribute("same", booksList);
            model.addAttribute("sameBorrow",sameBorrow);
            model.addAttribute("sameStar", sameStar);
            model.addAttribute("star", star);
            model.addAttribute("borrow", borrow);
            model.addAttribute("commentList", commentList);
            model.addAttribute("comment", comment);
        }
        return "borrower/borrowerBookDetail";
    }
    @ApiOperation(value = "读者信誉页面")
    @GetMapping("/borrowerCredit")
    public String borrowerCreditInfo(HttpServletRequest request, Model model){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        int borrowerId = (int) request.getSession().getAttribute("id");
        int count = creditService.selectIsBreach(borrowerId);
        model.addAttribute("isBreach",count==0?0:1);
        return "borrower/borrowerCredit";
    }
    @ApiOperation(value = "读者信誉详情")
    @GetMapping("/borrowerCreditInfo")
    @ResponseBody
    public JsonObject borrowerCreditInfo(int page, int limit, HttpServletRequest request){
        int borrowerId = (int)request.getSession().getAttribute("id");
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        List<Credit> credits = creditService.selectByBorrowerId(borrowerId,page,limit);
        for (Credit info : credits) {
            if (info.getIsBreach()) {
                info.setIs("是");
            } else {
                info.setIs("否");
            }

        }
        jsonObject.setData(credits);
        jsonObject.setCount((long)creditService.selectByBorrowerIdCount(borrowerId));
        //System.out.println(commentInfo);
        return jsonObject;
    }
    @ApiOperation(value = "读者修改书评页面")
    @GetMapping("/borrowerCommentUpdate")
    public String borrowerCommentUpdate(int id, Model model, HttpServletRequest request){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        Comment comment = commentService.selectCommentById(id);
        model.addAttribute("comment", comment);
        return "borrower/borrowerCommentUpdate";
    }
    @ApiOperation(value = "读者书评修改")
    @PostMapping("/updateBorrowerComment")
    @ResponseBody
    public R updateComment(@RequestParam("id") Integer id,
                           @RequestParam("content") String content,
                           @RequestParam("score") Integer score,
                           HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        Comment comment = commentService.selectCommentById(id);
        if(score.equals(comment.getScore()) && content.equals(comment.getContent())){
            return R.fail("您未进行修改");
        }
        int oldScore = comment.getScore();
        comment.setContent(content);
        comment.setScore(score);
        if(commentService.updateCommentById(id,comment,oldScore) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后重试");
        }
    }
    @ApiOperation(value = "读者借阅图书页面")
    @GetMapping("/borrowBook")
    public String borrowBook(Model model, HttpServletRequest request, String bookName){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        Books books = booksService.selectByNameOnly(bookName);
        if(books != null){
            //System.out.println(books);
            Times times = timesService.selectByName(books.getName());
            times.setClickTimes(times.getClickTimes() + 1);
            timesService.updateClickTimes(times);
            //System.out.println(a);
            List<Books> booksList = booksService.selectByISBN1(books.getISBN());
            List<Borrow> borrow = borrowService.selectLastBorrow(bookName);
            List<Order> order = orderService.selectByBookName(bookName);
            List<Books> sameBorrow = booksService.selectBySameBorrower(books.getName());
            List<Books> sameStar = booksService.selectBySameStar(books.getName());
            List<Comment> commentList = commentService.selectByBookName(books.getName());
            for (Comment comment : commentList) {
                String temp = comment.getBorrowerName().substring(0, 1);
                temp = temp + "**";
                comment.setBorrowerName(temp);
            }
            //System.out.println(borrow);
            model.addAttribute("same", booksList);
            model.addAttribute("borrow", borrow);
            model.addAttribute("order", order);
            model.addAttribute("sameBorrow",sameBorrow);
            model.addAttribute("sameStar", sameStar);
            model.addAttribute("comment", commentList);
        }
        return "borrower/borrowBook";
    }
    @ApiOperation(value = "读者借阅")
    @PostMapping("/borrow")
    @ResponseBody
    public R borrow(@RequestParam("bookId") int bookId,
                    @RequestParam("end") String endString,
                    HttpServletRequest request) throws ParseException {
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        String name = (String)request.getSession().getAttribute("name");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        Borrower borrower = borrowerService.selectById((int)request.getSession().getAttribute("id"));
        if(borrower.getBreach()){
            return R.fail("您正在冻结期，无法借阅！");
        }
        Books book = booksService.selectById(bookId);
        if(book.getBorrown()){
            return R.fail("该图书已被借阅");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date start = new Date();
        Date end = simpleDateFormat.parse(endString);
        if((end.getTime() - start.getTime()) / (1000 * 3600 * 24) > 30){
            return R.fail("借书时间不能超过30天");
        }
        java.sql.Date sqlDateStart = new java.sql.Date(start.getTime());
        java.sql.Date sqlDateEnd = new java.sql.Date(end.getTime());
        List<Order> orders = orderService.selectByBookIdAndEndDate(bookId, sqlDateStart);
        for (int i = 0; i < orders.size(); ++i){
            Date orderStart = orders.get(i).getStartDate();
            if(!end.before(orderStart)){
                if(orders.get(i).getBorrowerName().equals(name)){
                    orderService.deleteOrderById(orders.get(i).getId());
                    return R.ok();
                }
                String s = orders.get(i).getStartDate().toString();
                String e = orders.get(i).getEndDate().toString();
                return R.fail("借阅失败，在" + s + "到" + e + "中已有人预约这本书");
            }
        }
        Borrow borrow = new Borrow();
        borrow.setBookId(bookId);
        borrow.setBookName(book.getName());
        borrow.setBorrowerId((int)request.getSession().getAttribute("id"));
        borrow.setBorrowerName((String)request.getSession().getAttribute("name"));
        borrow.setStart(sqlDateStart);
        borrow.setEnd(sqlDateEnd);
        borrow.setIsReturn(false);
        borrowService.insertBorrow(borrow, bookId);
        return R.ok();
    }
    @ApiOperation(value = "读者预约")
    @PostMapping("/order")
    @ResponseBody
    public R order(@RequestParam("bookId") int bookId,
                    @RequestParam("start") String startString,
                    @RequestParam("end") String endString,
                    HttpServletRequest request) throws ParseException {
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        Borrower borrower = borrowerService.selectById((int)request.getSession().getAttribute("id"));
        if(borrower.getBreach()){
            return R.fail("您正在冻结期，无法预约！");
        }
        Books book = booksService.selectById(bookId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date start = simpleDateFormat.parse(startString);
        Date end = simpleDateFormat.parse(endString);
        if(end.getTime() - start.getTime() < 0){
            return R.fail("时间错误");
        }
        if((end.getTime() - start.getTime()) / (1000 * 3600 * 24) > 30){
            return R.fail("预约时长不能超过30天");
        }
        java.sql.Date sqlDateStart = new java.sql.Date(start.getTime());
        java.sql.Date sqlDateEnd = new java.sql.Date(end.getTime());
        List<Order> orders = orderService.selectByBookIdAndEndDate(bookId, sqlDateStart);
        for (int i = 0; i < orders.size(); ++i){
            Date orderStart = orders.get(i).getStartDate();
            if(!end.before(orderStart)){
                String s = orders.get(i).getStartDate().toString();
                String e = orders.get(i).getEndDate().toString();
                return R.fail("预约失败，在" + s + "到" + e + "中已有人预约这本书");
            }
        }
        Order order = new Order();
        order.setBorrowerId((int)request.getSession().getAttribute("id"));
        order.setBorrowerName((String)request.getSession().getAttribute("name"));
        order.setBookId(bookId);
        order.setBookName(book.getName());
        order.setStartDate(sqlDateStart);
        order.setEndDate(sqlDateEnd);
        orderService.insertOrder(order);
        return R.ok();
    }
    @ApiOperation(value = "读者还书")
    @PostMapping("/return")
    @ResponseBody
    public R returnBook(HttpServletRequest request,
                        @RequestParam("id") Integer id,
                        @RequestParam("pwd") String pwd){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        String p = (String)request.getSession().getAttribute("password");
        //System.out.println(p);
        //System.out.println(pwd);
        if(!p.equals(pwd)){
            return R.fail("密码错误");
        }
        //System.out.println(borrowService.selectIsReturn(id));
        if(borrowService.selectIsReturn(id) == 1){
            return R.fail("您已归还此书");
        }
        //System.out.println(111);
        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        if(borrowService.updateReturn(sqlDate,id) == 0){
            //System.out.println(222);
            return R.ok();
        }else{
            return R.fail("请稍后再试");
        }
    }
    @ApiOperation(value = "读者续借页面")
    @GetMapping("/renewBook")
    public String renewBook(HttpServletRequest request, Model model, Integer bookId){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return "notLogin";
        }
        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());

        Books books = booksService.selectById(bookId);
        if(books != null){
            //System.out.println(books);
            List<Order> orders = orderService.selectByBookIdAndEndDate(bookId, sqlDate);
            Borrow borrow = borrowService.selectLastBorrowByBookId(bookId);
            //System.out.println(a);
            List<Books> booksList = booksService.selectByISBN1(books.getISBN());
            List<Books> sameBorrow = booksService.selectBySameBorrower(books.getName());
            List<Books> sameStar = booksService.selectBySameStar(books.getName());
            List<Comment> commentList = commentService.selectByBookName(books.getName());
            for (Comment comment : commentList) {
                String temp = comment.getBorrowerName().substring(0, 1);
                temp = temp + "**";
                comment.setBorrowerName(temp);
            }
            //System.out.println(borrow);
            Calendar calendar = new GregorianCalendar();
            if(borrow != null){
                calendar.setTime(borrow.getEnd());
            }
            calendar.add(Calendar.DATE, 30);
            Date newDate = calendar.getTime();
            java.sql.Date newSqlDate = new java.sql.Date(newDate.getTime());
            model.addAttribute("newDate", newSqlDate);
            model.addAttribute("same", booksList);
            model.addAttribute("borrow", borrow);
            model.addAttribute("order", orders);
            model.addAttribute("sameBorrow",sameBorrow);
            model.addAttribute("sameStar", sameStar);
            model.addAttribute("comment", commentList);
        }
        return "borrower/renewBook";
    }
    @ApiOperation(value ="读者续借")
    @PostMapping("/renew")
    @ResponseBody
    public R renew(HttpServletRequest request, @RequestParam(value = "bookId",required = false) Integer bookId,
                        @RequestParam(value = "end",required = false) String endString,
                   @RequestParam("oldEnd") String oldEndString) throws ParseException {
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null) {
            return R.fail("您没有权限");
        }
        if(bookId == null){
            return R.fail("用户未借阅此书");
        }
        Borrower borrower = borrowerService.selectById((int)request.getSession().getAttribute("id"));
        if(borrower.getBreach()){
            return R.fail("您正在冻结期，无法借阅！");
        }
        Books book = booksService.selectById(bookId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date end = simpleDateFormat.parse(endString);
        Date oldEnd = simpleDateFormat.parse(oldEndString);
        java.sql.Date sqlDateEnd = new java.sql.Date(end.getTime());
        java.sql.Date sqlDateOldEnd = new java.sql.Date(oldEnd.getTime());
        String name = (String)request.getSession().getAttribute("name");
        List<Order> orders = orderService.selectByBookIdAndEndDate(bookId, sqlDateOldEnd);
        for (int i = 0; i < orders.size(); ++i){
            Date orderStart = orders.get(i).getStartDate();
            if(!end.before(orderStart)){
                if(orders.get(i).getBorrowerName().equals(name)){
                    orderService.deleteOrderById(orders.get(i).getId());
                    return R.ok();
                }
                String s = orders.get(i).getStartDate().toString();
                String e = orders.get(i).getEndDate().toString();
                return R.fail("借阅失败，在" + s + "到" + e + "中已有人预约这本书");
            }
        }
        Borrow borrow = borrowService.selectLastBorrowByBookId(bookId);
        if(borrow == null){
           return R.fail("用户未借阅此书");
        }
        Date start = new Date(borrow.getStart().getTime());
        if((end.getTime() - start.getTime()) / (1000 * 3600 * 24) > 30){
            return R.fail("借书时间不能超过30天");
        }
        borrow.setEnd(sqlDateEnd);
        if(borrowService.updateRenew(sqlDateEnd, borrow.getId()) == 0){
            return R.ok();
        }
        return R.fail("请稍后重试");
    }
    @ApiOperation(value ="读者收藏图书")
    @PostMapping("/starBook")
    @ResponseBody
    public R starBook(HttpServletRequest request, @RequestParam("bookId") Integer bookId,
                      @RequestParam("bookName") String bookName){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        Integer borrowerId = (Integer) request.getSession().getAttribute("id");
        String borrowerName = (String) request.getSession().getAttribute("name");
        if(starService.selectExist(bookName, borrowerId) == 0){
            Star star = new Star();
            star.setBookId(bookId);
            star.setBorrowerId(borrowerId);
            star.setBorrowerName(borrowerName);
            star.setBookName(bookName);
            if(starService.insertStar(star) == 0){
                return R.ok();
            }
            return R.fail("数据库忙，请稍后再试");
        }
        return R.fail("您已经收藏过该书籍");
    }
    @ApiOperation(value ="读者评论")
    @PostMapping("/addComment")
    @ResponseBody
    public R addComment(@RequestParam(value = "id", required = false) Integer id,
                        @RequestParam("content") String content,
                        @RequestParam("score") Integer score,
                        @RequestParam("bookId") Integer bookId,
                        @RequestParam("bookName") String bookName,
                        HttpServletRequest request){
        String isLongin = (String)request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return R.fail("您没有权限");
        }
        Integer borrowerId = (Integer) request.getSession().getAttribute("id");
        String borrowerName = (String) request.getSession().getAttribute("name");
        if(commentService.selectExist(bookName,borrowerId) == 0){
            Comment comment = new Comment();
            comment.setBorrowerId(borrowerId);
            comment.setBookId(bookId);
            comment.setBookName(bookName);
            comment.setBorrowerName(borrowerName);
            comment.setContent(content);
            comment.setScore(score);
            if(commentService.insertComment(comment) == 0){
                return R.ok();
            }else {
                return R.fail("数据库错误，请稍后重试");
            }
        }
        if(id == null){
            return R.fail("请关闭页面重试！");
        }
        Comment comment = commentService.selectCommentById(id);
        if(score.equals(comment.getScore()) && content.equals(comment.getContent())){
            return R.fail("您未进行修改");
        }
        int oldScore = comment.getScore();
        comment.setContent(content);
        comment.setScore(score);
        if(commentService.updateCommentById(id,comment,oldScore) == 0){
            return R.ok();
        }else {
            return R.fail("数据库错误，请稍后重试");
        }
    }
    @ApiOperation(value ="读者搜索书籍")
    @GetMapping("/borrowerBookSearch")
    public String borrowerBookSearch(HttpServletRequest request){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        return "borrower/borrowerBookSearch";
    }
    @ApiOperation(value ="读者搜索书籍详情")
    @GetMapping("/borrowerBooksSearchDetail")
    @ResponseBody
    public JsonObject borrowerBooksSearch(int page, int limit, int op, String title){
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        jsonObject.setCount((long)booksService.selectCount());
        List<Books> booksList = null;
        if(op == 0){
            title = '%' + title + '%';
            booksList = booksService.selectByName(title,page,limit);
        }else if(op == 1){
            title = '%' + title + '%';
            booksList = booksService.selectByAuthor(title,page,limit);
        }else if(op == 2){
            title = '%' + title + '%';
            booksList = booksService.selectByPublishingHouse(title,page,limit);
        }else if(op == 3){
            title = '%' + title + '%';
            booksList = booksService.selectByPublishDate(title,page,limit);
        }else if(op == 4){
            title = '%' + title + '%';
            booksList = booksService.selectByISBN(title,page,limit);
        }
        //System.out.println(booksList);
        if(booksList != null){
            for(Books book : booksList){
                Times times = timesService.selectByName(book.getName());
                times.setSearchTimes(times.getSearchTimes() + 1);
                timesService.updateSearchTimes(times);
            }
        }
        //System.out.println(booksList);
        jsonObject.setData(booksList);
        return jsonObject;
    }
    @ApiOperation(value ="读者书籍排名")
    @GetMapping("/borrowerBookRank")
    public String borrowerBookRank(Model model,HttpServletRequest request){
        String isLongin = (String) request.getSession().getAttribute("isLogin");
        if (isLongin == null || !isLongin.equals("1")) {
            return "notLogin";
        }
        List<Books> borrowRank = booksService.selectBookByBorrowDesc(1, 10);
        List<Books> searchRank = booksService.selectBookBySearchDesc(1, 10);
        List<Books> starRank = booksService.selectBookByStarDesc(1, 10);
        List<Books> scoreRank = booksService.selectByScoreDesc(1, 10);
        List<Books> clickRank = booksService.selectBookByClickDesc(1, 10);
        model.addAttribute("borrowRank", borrowRank);
        model.addAttribute("searchRank", searchRank);
        model.addAttribute("starRank", starRank);
        model.addAttribute("scoreRank", scoreRank);
        model.addAttribute("clickRank", clickRank);
        return "visitor/visitorBookRank";
    }
    @ApiOperation(value ="读者书籍排名详情")
    @GetMapping("/borrowerBooksRankInfo")
    @ResponseBody
    public JsonObject borrowerBooksRankInfo(int page, int limit, int id){
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        jsonObject.setCount((long)booksService.selectCount());
        List<Books> booksList = null;
        if(id == 1){
            booksList = booksService.selectBookByBorrowDesc(page, limit);
        }else if(id == 2){
            booksList = booksService.selectBookBySearchDesc(page, limit);
        }else if(id == 3){
            booksList = booksService.selectBookByStarDesc(page, limit);
        }else if(id == 4){
            booksList = booksService.selectByScoreDesc(page, limit);
        }else if(id == 5){
            booksList = booksService.selectBookByClickDesc(page, limit);
        }
        jsonObject.setData(booksList);
        return jsonObject;
    }
    @GetMapping("/borrowerBooksInfo")
    @ResponseBody
    public JsonObject borrowerBooksInfo(int page, int limit,
                                       @RequestParam(value="type", required = false) String type){
        JsonObject jsonObject =new JsonObject();
        jsonObject.setCode(0);
        jsonObject.setMsg("ok");
        jsonObject.setCount((long)booksService.selectCount());
        List<Books> booksList = null;
        if(type == null){
            booksList = booksService.selectAllByLimit(page, limit);
        } else {
            String c = '%'+type+'%';
            booksList = booksService.selectAllByClassification(c,page,limit);
            //System.out.println(booksList);
        }
        //System.out.println(booksList);
        jsonObject.setData(booksList);
        return jsonObject;
    }
}
